package com.rzgeo.rzmaplib.comp;

import android.content.Context;
import android.support.annotation.Nullable;
import android.text.InputType;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseExpandableListAdapter;
import android.widget.ExpandableListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.esri.arcgisruntime.data.Feature;
import com.esri.arcgisruntime.data.Field;
import com.rzgeo.rzmaplib.R;
import com.rzgeo.rzmaplib.RmlFeatureLayerQueryHelper;
import com.rzgeo.rzmaplib.util.RmlData;
import com.rzgeo.rzmaplib.util.RmlUtil;

import java.util.ArrayList;

/**
 * Created by zhanghang on 2018/1/27.
 */

public class RmlFeatureInfo extends LinearLayout {
    private ExpandableListView _expandableListView;
    private ArrayList<RmlData.FeatureLayerData> _features;
    private ExAdapter _exAdapter;

    public RmlFeatureInfo(Context context) {
        super(context);
        initUI(context);
    }

    public RmlFeatureInfo(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initUI(context);
    }

    public RmlFeatureInfo(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initUI(context);
    }

    private void initUI(Context context) {
        View subView = LayoutInflater.from(context).inflate(R.layout.comp_feature_info, null);
        subView.setLayoutParams(
                new FrameLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,ViewGroup.LayoutParams.WRAP_CONTENT));
        this.addView(subView);
    }

    @Override
    protected void onFinishInflate() {
        super.onFinishInflate();
        _expandableListView = this.findViewById(R.id.elv_feature_detail);

    }

    public void setup(RmlFeatureLayerQueryHelper.QueryResult[] queryResult, int showIndex) {
        _features = new ArrayList<>();
//        _featureAttrs = new ArrayList<>();
        for(RmlFeatureLayerQueryHelper.QueryResult qr:queryResult){
            if(qr==null||qr.features==null)
                continue;
            ArrayList<Feature>selFeas=new ArrayList<>();
            for(Feature f:qr.features){
                _features.add(new RmlData.FeatureLayerData(f,qr.layer));
                selFeas.add(f);
            }
            qr.layer.clearSelection();
            qr.layer.selectFeatures(selFeas);
        }

        _exAdapter = new ExAdapter(getContext(),_features);
        _expandableListView.setAdapter(_exAdapter);
        if(_features!=null&&_features.size()>0){

            _expandableListView.expandGroup(showIndex);//设置第一组张开
            //_expandableListView.collapseGroup(0); 将第group组收起
            _expandableListView.setGroupIndicator(null);//除去自带的箭头，自带的箭头在父列表的最左边，不展开向下，展开向上
            _expandableListView.setDivider(null);//这个是设定每个Group之间的分割线。,默认有分割线，设置null没有分割线

            _expandableListView.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {

                @Override
                public boolean onChildClick(ExpandableListView parent, View v, int groupPosition, int childPosition, long id) {
                    _exAdapter.setChildSelection(groupPosition,childPosition);
                    _exAdapter.notifyDataSetChanged();
                    return true;
                }

            });
        }
    }

    public static class ExAdapter extends BaseExpandableListAdapter
    {
        private final Context context;
        private final ArrayList<RmlData.FeatureLayerData> features;
        private final LayoutInflater inflater;

        int selectParentItem = -1;
        int selectChildItem = -1;

        public ExAdapter(Context context, ArrayList<RmlData.FeatureLayerData> features) {
            this.context = context;
            this.features=features;
            this.inflater=LayoutInflater.from(context);
        }

        public void setChildSelection(int groupPosition, int childPosition)
        {
            selectParentItem = groupPosition;
            selectChildItem = childPosition;
        }

        @Override
        public Object getChild(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            RmlData.FeatureLayerData fh = features.get(groupPosition);
            return fh.feature.getAttributes().get(fh.layer.getFeatureTable().getFields().get(childPosition).getName());
        }

        @Override
        public long getChildId(int groupPosition, int childPosition) {
            // TODO Auto-generated method stub
            return groupPosition*1000+childPosition;
        }

        @Override
        public View getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView,
                                 ViewGroup parent) {
            ViewHolder4Attrs holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.comp_feature_info_feature_attrs, null);
                holder = new ViewHolder4Attrs(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder4Attrs) convertView.getTag();
            }
            RmlData.FeatureLayerData fh = features.get(groupPosition);
            Field field = fh.layer.getFeatureTable().getFields().get(childPosition);
            holder.setData(fh.feature.getAttributes().get(field.getName()),field);
            if (selectChildItem == childPosition && selectParentItem == groupPosition)
            {
                Log.i("++++++++++", "点击："+groupPosition+","+childPosition);
            }

            return convertView;
        }

        @Override
        public int getChildrenCount(int groupPosition) {
            // TODO Auto-generated method stub
            return features.get(groupPosition).layer.getFeatureTable().getFields().size();
        }

        @Override
        public Object getGroup(int groupPosition) {
            // TODO Auto-generated method stub
            return features.get(groupPosition);
        }

        @Override
        public int getGroupCount() {
            // TODO Auto-generated method stub
            return features.size();
        }

        @Override
        public long getGroupId(int groupPosition) {
            // TODO Auto-generated method stub
            return groupPosition;
        }

        @Override
        public View getGroupView(int groupPosition, boolean isExpanded, View convertView,
                                 ViewGroup parent) {
            ViewHolder4Feature holder;
            if (convertView == null) {
                convertView = inflater.inflate(R.layout.comp_feature_info_feature, null);
                holder = new ViewHolder4Feature(convertView,context);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder4Feature) convertView.getTag();
            }
            holder.setData(features.get(groupPosition),groupPosition,isExpanded);

            return convertView;
        }

        @Override
        public boolean hasStableIds() {
            return true;
        }

        @Override
        public boolean isChildSelectable(int groupPosition, int childPosition) {
            return true;
        }

        public static class ViewHolder4Feature {

            private final TextView txvLayer;
            private final TextView txvId;
            private final ImageView imgFold;
            private final Context _context;
            private RmlData.FeatureLayerData _fld;

            public ViewHolder4Feature(View convertView,Context context) {
                _context=context;
                txvLayer=convertView.findViewById(R.id.txv_layer);
                txvId=convertView.findViewById(R.id.txv_id);
                imgFold=convertView.findViewById(R.id.img_fold);
            }

            public void setData(RmlData.FeatureLayerData featureLayerData, int gourpIndex, boolean isExpanded) {
                _fld =featureLayerData;

                if(isExpanded){
                    imgFold.setImageDrawable(_context.getResources().getDrawable( R.drawable.icad_fold));
                }
                else{
                    imgFold.setImageDrawable(_context.getResources().getDrawable( R.drawable.icad_unfold));
                }

                txvLayer.setText(_fld.layer.getName());
                for(Field f: _fld.layer.getFeatureTable().getFields()){
                    if(f.getFieldType()== Field.Type.OID){
                        txvId.setText(_fld.feature.getAttributes().get(f.getName()).toString());
                        return;
                    }
                }
                txvId.setText(Integer.toString(gourpIndex));

            }
        }

        public static class ViewHolder4Attrs {

            private final TextView txvName;
            private final TextView tinValue;

            public ViewHolder4Attrs(View convertView) {
                txvName=convertView.findViewById(R.id.txv_field);
                tinValue=convertView.findViewById(R.id.tin_value);
                tinValue.setSingleLine();
            }

            public void setData(Object o, Field field) {
                if(RmlUtil.isValid(field.getAlias()))
                    txvName.setText(field.getAlias());
                else
                    txvName.setText(field.getName());

                boolean editable=false;
                Field.Type t = field.getFieldType();
                if(t== Field.Type.INTEGER||t==Field.Type.SHORT){
                    tinValue.setText(o==null?"":o.toString());
                    tinValue.setInputType(InputType.TYPE_CLASS_NUMBER|InputType.TYPE_NUMBER_FLAG_SIGNED);
                    editable=true;
                }else if(t== Field.Type.DOUBLE||t==Field.Type.FLOAT){
                    tinValue.setText(o==null?"":o.toString());
                    tinValue.setInputType(InputType.TYPE_NUMBER_FLAG_SIGNED|InputType.TYPE_NUMBER_FLAG_DECIMAL);
                    editable=true;
                }else if(t== Field.Type.DATE){
                    tinValue.setText(RmlUtil.Convert.toDateString(o));
                    tinValue.setInputType(InputType.TYPE_CLASS_DATETIME|InputType.TYPE_DATETIME_VARIATION_DATE);
                    editable=true;
                }else if(t== Field.Type.TEXT){
                    tinValue.setText(o==null?"":(String)o);
                    tinValue.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_NORMAL);
                    editable=true;
                }else if(t== Field.Type.GLOBALID||t== Field.Type.GUID||t== Field.Type.OID){
                    tinValue.setText(o==null?"":o.toString());
                    tinValue.setInputType(InputType.TYPE_CLASS_TEXT|InputType.TYPE_TEXT_VARIATION_NORMAL);
                    editable=false;
                }else{
                    tinValue.setText("不支持查看");
                    editable=false;
                }

                if(editable){
                    tinValue.setFocusableInTouchMode(true);
                    tinValue.setFocusable(true);
                    tinValue.requestFocus();
                }else{
                    tinValue.setFocusable(false);
                    tinValue.setFocusableInTouchMode(false);
                }
            }
        }
    }
}
